#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "textitemwidget.h"
#include <QPrinter>
#include <QPrintDialog>
#include <QPainter>
#include <QDebug>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFileDialog>
#include <QLineEdit>
#include <QDoubleSpinBox>
#include <QMessageBox>
#include <QAxObject>
#include <QProgressDialog>
#include <QtPdf/QPdfDocument>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 隐藏最大化和最小化按钮
    this->setWindowFlags(this->windowFlags() & ~Qt::WindowMinMaxButtonsHint);

    ui->tabWidget->setTabsClosable(true);
    connect(ui->tabWidget,&QTabWidget::tabCloseRequested,this,&MainWindow::SlottabCloseRequested);

    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &MainWindow::postBack);//通信完成后，自动执行getBack

    ui->widget_2->setFixedHeight(400);
    ui->widget_2->setWeekNameFormat(LunarCalendarWidget::WeekNameFormat::WeekNameFormat_Short);
    connect(ui->widget_2, &LunarCalendarWidget::selectclicked, this,&MainWindow::SlotcalendarWidgetselectionChanged);
    SlotcalendarWidgetselectionChanged(QDate::currentDate());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_2_clicked()
{
    QPrinter printer;
    printer.setPageSize(QPageSize::PageSizeId::A4);
    printer.setPageOrientation(QPageLayout::Orientation::Portrait);
    // QPrintDialog printDialog(&printer);

    //if (printDialog.exec() == QDialog::Accepted) {
    for(int i = 0;i < m_totaldata.size();i++)
    {
        ui->label_5->UpdateText(m_totaldata.at(i));
        QPainter painter;
        painter.setRenderHint(QPainter::Antialiasing, true);  // 启用抗锯齿
        painter.setRenderHint(QPainter::TextAntialiasing, true);  // 启用文本抗锯齿
        if (painter.begin(&printer)) {
            // 计算QWidget的大小和打印区域
            QRect rect = painter.viewport();
            QSize widgetSize = ui->label_5->size();
            QRectF targetRect = QRectF(0, 0, rect.width(), rect.height());
            // 缩放比例，保持内容按比例适配 A4 纸
            qreal scaleX = targetRect.width() / widgetSize.width();
            qreal scaleY = targetRect.height() / widgetSize.height();
            qreal scale = qMin(scaleX, scaleY);
            painter.scale(scale, scale);
            int x = (rect.width() - widgetSize.width() * scale) / 2;
            int y = (rect.height() - widgetSize.height() * scale) / 2;
            // 将 QWidget 绘制到打印机上
            ui->label_5->render(&painter, QPoint(x,y));
            // 完成打印
            painter.end();
        }
    }
    //}
}

void MainWindow::SlotcalendarWidgetselectionChanged(const QDate &selectDate)
{
    QNetworkRequest quest;
    quest.setUrl(QUrl(QString("http://124.220.49.230/api/time/getzdday.php?id=88888888&key=88888888&nian=%1&yue=%2&ri=%3")
                          .arg(selectDate.year())
                          .arg(selectDate.month())
                          .arg(selectDate.day())));
    QNetworkReply *reply = manager->get(quest);
    reply->setProperty("id", 1);
    //开启事件循环，直到请求完成
    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
}

void MainWindow::postBack(QNetworkReply *reply)
{
    int id = reply->property("id").toInt(); // 获取自定义标识符
    if (reply->error() == QNetworkReply::NoError)
    {
        // 读取响应内容
        QByteArray response = reply->readAll();
        switch (id)
        {
        case 1:
        {
            // 将JSON字符串转换为JSON文档对象
            QJsonDocument doc = QJsonDocument::fromJson(response);
            // 获取JSON对象
            QJsonObject obj = doc.object();
            // 解析JSON对象中的各个字段
            int code = obj.value("code").toInt();
            //登录成功
            if (code == 200)
            {
                QString year = obj.value("ganzhinian").toString();
                QString month = obj.value("ganzhiyue").toString();
                QString day = obj.value("ganzhiri").toString();
                ui->label_4->setText(QString("%1 %2 %3").arg(year).arg(month).arg(day));
            }
        }
        break;
        }
    }
    else
    {
        // 输出错误信息
        qDebug() << "Error:" << reply->errorString();
    }
}

void MainWindow::on_actionPic_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral(""),
                                                    QApplication::applicationDirPath(),
                                                    tr("Images (*.png *.xpm *.jpg)"));
    if(!fileName.isEmpty())
    {
        QPixmap pixmap(fileName);
        ui->label_5->setPixmap(pixmap);
    }
}

void MainWindow::on_btn_enable_clicked()
{
    // 禁用所有 QPushButton 类型的控件
    QList<QPushButton*> buttons = this->findChildren<QPushButton*>();
    for (QPushButton *button : buttons) {
        if(button->objectName() != "btn_enable")
        {
            button->setEnabled(!button->isEnabled());  // 禁用按钮
        }
    }

    // 禁用所有 QLineEdit 类型的控件
    QList<QLineEdit*> lineEdits = this->findChildren<QLineEdit*>();
    for (QLineEdit *lineEdit : lineEdits) {
        lineEdit->setEnabled(!lineEdit->isEnabled());  // 禁用输入框
    }

    // 禁用所有 QLineEdit 类型的控件
    QList<QDoubleSpinBox*> doubleSpinBoxs = this->findChildren<QDoubleSpinBox*>();
    for (QDoubleSpinBox *doubleSpinBox : doubleSpinBoxs) {
        doubleSpinBox->setEnabled(!doubleSpinBox->isEnabled());  // 禁用输入框
    }

    // 禁用所有 QAction 类型的控件
    QList<QAction*> actions = this->findChildren<QAction*>();
    for (QAction *action : actions) {
        action->setEnabled(!action->isEnabled());  // 禁用QAction
    }
}

void MainWindow::on_btn_AddText_clicked()
{
    if(!ui->label_5->getPixmap().isNull())
    {
        //获取最大下标
        int maxindex = -1;
        QMapIterator<int, TextItemWidget*> i(TextItemWidgetHash);
        while (i.hasNext()) {
            i.next();
            if(i.key() > maxindex)
                maxindex = i.key();
        }
        maxindex++;
        TextItemWidget* item = new TextItemWidget(maxindex);
        connect(item,&TextItemWidget::SignalUpdata,[=](const TextInfos& info){
            ui->label_5->UpdateTextInfo(info);
        });
        ui->tabWidget->addTab(item, QString("文字%1").arg(maxindex+1));
        TextItemWidgetHash.insert(maxindex, item);
        ui->tabWidget->setCurrentIndex(ui->tabWidget->count()-1);
    }
    else
    {
        QMessageBox::warning(this,QStringLiteral("提示"),QStringLiteral("请先导入模版！"),QMessageBox::Ok);
    }
}

void MainWindow::SlottabCloseRequested(int index)
{
    QMap<int, TextItemWidget*>::const_iterator i = TextItemWidgetHash.constBegin();
    while (i != TextItemWidgetHash.constEnd()) {
        if(ui->tabWidget->widget(index) == i.value())
        {
            TextItemWidgetHash.remove(i.key());
            ui->label_5->removeTextInfo(i.key());
            break;
        }
        ++i;
    }
    ui->tabWidget->removeTab(index);
}

void MainWindow::on_action_excel_triggered()
{
    QString filePath = QFileDialog::getOpenFileName(this,QStringLiteral(""),
                                                    QApplication::applicationDirPath(),
                                                    QStringLiteral("Excel文件 (*.xl *.xlsx )"));
    if(!filePath.isEmpty())
    {
        QProgressDialog progress(this);
        progress.setLabelText("Abort Copy");
        progress.setWindowModality(Qt::WindowModal);
        progress.setRange(0, 100);
        progress.show();
        progress.setValue(1);
        QApplication::processEvents();
        // 创建 Excel 应用对象
        QAxObject *excel = new QAxObject("Excel.Application");
        excel->setProperty("Visible", false);  // 隐藏 Excel 窗口
        progress.setValue(2);
        QApplication::processEvents();
        // 打开 Excel 文件
        QAxObject *workbooks = excel->querySubObject("Workbooks");
        QAxObject *workbook = workbooks->querySubObject("Open(const QString&)", filePath);
        progress.setValue(3);
        QApplication::processEvents();
        // 获取第一个工作表
        QAxObject *sheet = workbook->querySubObject("Sheets(int)", 1);
        progress.setValue(4);
        QApplication::processEvents();
        // 获取工作表中使用的范围
        QAxObject *usedRange = sheet->querySubObject("UsedRange");
        QAxObject *rows = usedRange->querySubObject("Rows");
        int rowCount = rows->property("Count").toInt();
        progress.setRange(0, rowCount);
        QAxObject *Columns = usedRange->querySubObject("Columns");
        int ColumnCount = Columns->property("Count").toInt();

        m_totaldata.clear();
        // 读取每一行的两列数据
        for (int row = 1; row <= rowCount; ++row) {
            progress.setValue(row);
            QApplication::processEvents();
            QList<QVariant> temp;
            for(int column = 1;column<=ColumnCount;++column)
            {
                QAxObject *cell1 = sheet->querySubObject("Cells(int,int)", row, column);  // 读取第一列（A列）
                QVariant value1 = cell1->dynamicCall("Value");
                temp.append(value1);
            }
            m_totaldata.append(temp);
        }

        // 关闭工作簿
        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");
        if(m_totaldata.size() == 0)
        {
            QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("Excel文档数据为空！"), QMessageBox::Ok);
        }
        else
        {
            QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("数据加载成功！"), QMessageBox::Ok);
        }
    }
}

void MainWindow::on_actionWORD_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral(""),
                                                    QApplication::applicationDirPath(),
                                                    tr("Word文档 (*.docx *.doc )"));
    if(!fileName.isEmpty())
    {
        if(fileName.contains(' '))
        {
            QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("模版文件路径包含空格, 请重新选择！"), QMessageBox::Ok);
            return;
        }
        QProgressDialog progress(this);
        progress.setLabelText("Abort Copy");
        progress.setWindowModality(Qt::WindowModal);
        progress.setRange(0, 100);
        progress.show();
        progress.setValue(1);
        QApplication::processEvents();
        QString tempPDF = QStringLiteral("%1/temp.pdf").arg(QApplication::applicationDirPath());
        QFile file(tempPDF);
        if (file.exists()) {
            if (file.remove()) {
            }
        }
        QAxObject word("Word.Application");
        word.setProperty("Visible", false);
        progress.setValue(20);
        QApplication::processEvents();
        QAxObject* documents = word.querySubObject("Documents");
        QAxObject* document = documents->querySubObject("Open(QString)", fileName);
        progress.setValue(40);
        QApplication::processEvents();
        QVariant OutputFileName(tempPDF);
        QVariant ExportFormat(17);
        QVariant OpenAfterExport(false);
        document->querySubObject("ExportAsFixedFormat(const QVariant&,const QVariant&,const QVariant&)",
                                 OutputFileName,
                                 ExportFormat,
                                 OpenAfterExport);
        progress.setValue(60);
        QApplication::processEvents();
        document->dynamicCall("Close(boolean)", false);
        progress.setValue(80);
        QApplication::processEvents();
        word.dynamicCall("Quit (void)");
        progress.setValue(90);
        QApplication::processEvents();

        if(!openPDF(tempPDF))
        {
            progress.setValue(100);
            QApplication::processEvents();
            QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("模版文件页数错误, 请重新选择！"), QMessageBox::Ok);
        }
        progress.setValue(100);
        QApplication::processEvents();
    }
}

bool MainWindow::openPDF(const QString &filePath)
{
    QPdfDocument* document = new QPdfDocument;
    document->load(filePath);
    int totalPage = document->pageCount();
    if(totalPage != 1)
    {
        document->close();
        return false;
    }

    QSizeF size = document->pagePointSize(0);
    qreal scaleFactor = 3.0;  // 可以根据需要调整，2.0表示渲染的分辨率是默认的2倍
    QImage image = document->render(0, QSize(size.width() * scaleFactor, size.height() * scaleFactor));
    document->close();
    QPixmap pixmap = QPixmap::fromImage(image);
    ui->label_5->setPixmap(pixmap);
    return true;
}


void MainWindow::on_actionPDF_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral(""),
                                                    QApplication::applicationDirPath(),
                                                    tr("Pdf文档 (*.pdf )"));
    if(!fileName.isEmpty())
    {
        if(!openPDF(fileName))
        {
            QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("模版文件页数错误, 请重新选择！"), QMessageBox::Ok);
        }
    }
}

